/**
 * @author Nicolas Zimerman (zimerman@usi.ch)
 * @author Nicolas Latorre (nicolas.latorre@usi.ch)
 */

package ch.usi.inf.pf2.gui.action;

import javax.swing.ImageIcon;
import javax.swing.AbstractAction;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

import ch.usi.inf.pf2.file.interaction.InstructionWriter;
import ch.usi.inf.pf2.gui.CircuitFrame;
import ch.usi.inf.pf2.gui.Model;

import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.io.File;

public class QuitAction extends AbstractAction{
	
	private static final long serialVersionUID = -2519280232599486761L;
	private static JFileChooser fileChooser = new JFileChooser(System.getProperty("user.dir"));
	private final Model model;
	private final CircuitFrame circuitFrame;
	
	
	public QuitAction(final CircuitFrame circuitFrame, final Model model) {
		this.circuitFrame = circuitFrame;
		this.model = model;
		putValue(NAME, "Quit");
        final ImageIcon icon = new ImageIcon(getClass().getResource("../icons/quit.png"));
        putValue(SMALL_ICON, icon);
        putValue(SHORT_DESCRIPTION, "Load a file from the local machine.");

        setEnabled(true);
	}
	
	public void actionPerformed(final ActionEvent ev) {
		for(Frame frame : Frame.getFrames()) {
			if(frame.isVisible()) {
				ImageIcon icon = new ImageIcon(getClass().getResource("../icons/SaveDialog.png"));
				int result = JOptionPane.showConfirmDialog(frame, "Do you want to save before exit?", "", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, icon);
	    		if(result == 2) {
	    			return;
	    		}
	    		
	    		else if(result == 1) {
	    			((JFrame)frame).setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
	    			
	    		}
	    		else if(result == 0) {
	    			if(model.getCircuit() != null) {
	    	            int returnVal = fileChooser.showSaveDialog(circuitFrame);
	    	    
	    	            if(returnVal != JFileChooser.APPROVE_OPTION) {
	    	                return;
	    	            }
	    	            File selectedFile = fileChooser.getSelectedFile();
	    	            InstructionWriter writer = new InstructionWriter(selectedFile.getAbsolutePath(), model.getShapes());
	    	            ((JFrame) frame).setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
	    			}	
	    		}
			}
		}
		System.exit(0);
	}

}
